<?PHP

// This class is used as wrappers & decoration for artifacts
class folio_decoration {

    // Identifying information, uniquely ids any pieces of content, mapping back into Elgg.
    public $decoration_ident = -1;
    public $page_ident = -1;
	// Type can be set to 'private', in which case it is only shown to the owner of the decoration.
    public $type = 'label';
    public $newest = 1;

    // Created depending on the type of object.
    public $text = '';

    function handle() {
        return 'folio_decoration' . $this->decoration_ident;
    }

    // Constructor
    function folio_decoration( $array = false ) {
        // Assume constructor is an array from the db.
        if ( !!$array ) {
            foreach ( $array as $n=>$v ) {
                $this->$n = $v; //( $r . ' = ' . $v . '<br/>' );
            }
        }

    }

//////////////////
//              //
//  SQL Layer   //
//              //
//////////////////

    /**
     * Return all decorations for the page.
     * @param int $page_ident The page for which we're retrieving records
     * @param int $newest Optional, what is the status of the decorations we want?
     * @return array with a each matching item.
     */
    function SelectWherePageIdent( $page_ident, $newest = 1 ) {
        global $CFG;
        $decorations = array();

        $query = "SELECT a.decoration_ident, a.* FROM {$CFG->prefix}folio_decoration a " .
                    "WHERE a.page_ident = $page_ident and a.newest = $newest";

        $records = recordset_to_array( get_recordset_sql( $query ));

        if( !$records ) {return $decorations; }

        foreach( $records as $record ) {
				$decorations[$record->decoration_ident] = new folio_decoration( $record );;
        }

        return $decorations;
    }
	
	/**
	* Returns if the current user has access to the decoration.
	* Not used by the data layer, as we often will need to see a decoration.  Controlled via the decoration viewer and editor.
	**/
	public function Permission() {
		global $CFG;
		
		if ( $this->type == 'private' ) {
			if( !isloggedin ) {
				return false;
			} else {
			
				// Find page owner
				$page = folio_page::SelectWherePageIdent( $this->page_ident );
				return ( $page->user_ident == $_SESSION['userid']);
			}
		} else {
			return true;
		}
	}

    /**
     * Return a decoration
     * @param int $decoration_ident
     * @param int $newest Optional, what is the status of the decorations we want?
     * @return folio_decoration
     */
    function SelectWhereDecorationIdent( $decoration_ident, $newest = 1 ) {
        global $CFG;

        $query = "SELECT a.decoration_ident, a.* FROM {$CFG->prefix}" .
                    "folio_decoration a WHERE a.decoration_ident = " .
                    $decoration_ident . " AND newest = " . $newest;

        $d = recordset_to_array( get_recordset_sql( $query ));

        return new folio_decoration( $d[$decoration_ident] );
    }

    /**
     * Load decoration into the db, & return the resulting object with correct Ident.
     *
     * @param folio_decoration $d
     * @return folio_decoration
     */
    function Insert( $d ) {
        global $CFG;
        // Create a new record with the correct vars

        $i = new StdClass();
        foreach( $d as $n=>$v ){
            if( $n != 'decoration_ident' ) {
                $i->$n=$v;
            }
        }

        $decoration_ident = insert_record( 'folio_decoration', $i );

        // Load the new decoration from the db for the constructor.
        $d = folio_decoration::SelectWhereDecorationIdent( $decoration_ident );

        return $d;
    }

    /**
     * Update a decoration in the db.
     *
     * @param folio_decoration $decoration
     * @return folio_decoration Updated record
     */
    function Update( folio_decoration $decoration ) {

        return ( folio_decoration::local_update_record( 'folio_decoration', $decoration, 'decoration_ident' ) );
    }

    /**
     * Called to delete the record from the db
     *
     * Changes status to 0 so that it no longer shows up.
     *
     * @param int $artifact_ident
     * @return boolean Success
     */
    function Delete( $decoration_ident ) {
        $d = folio_decoration::SelectWhereDecorationIdent( $decoration_ident);
        $d->newest = 0;
        folio_decoration::Update($d);
        return true;
    }

    // This is a modification of update_record in datalib.php that is
    //      able to accept alternative ident column names.
    private function local_update_record($table, $dataobject, $ident) {
        global $db, $CFG;

        static $table_columns;

        // Determine all the fields in the table
        if (is_array($table_columns) && array_key_exists($table,$table_columns)) {
            $columns = $table_columns[$table];
        } else {
            if (!$columns = $db->MetaColumns($CFG->prefix . $table)) {
                return false;
            }
            $table_columns[$table] = $columns;
        }

        $data = (array)$dataobject;
        $ddd = array();

        if (defined('ELGG_PERFDB')) { global $PERF ; $PERF->dbqueries++; };

        // Pull out data matching these fields
        foreach ($columns as $column) {
            if ($column->name <> $ident and isset($data[$column->name]) ) {
                $ddd[$column->name] = $data[$column->name];
            }
        }

        // Construct SQL queries
        $numddd = count($ddd);
        $count = 0;
        $update = '';

        foreach ($ddd as $key => $value) {
            $count++;
            $update .= $key .' = ?';
            if ($count < $numddd) {
                $update .= ', ';
            }
        }

//return( 'UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'' );
        $stmt = $db->Prepare('UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'');
        if ($rs = $db->Execute($stmt,$ddd)) {
            elggcache_delete($table, "{$ident}_" . $dataobject->$ident);
            return true;
        } else {
            if (isset($CFG->debug) and $CFG->debug > 7) {
                notify($db->ErrorMsg() .'<br /><br />UPDATE '. $CFG->prefix . $table .' SET '. $update .' WHERE ' . $ident . ' = \''. $dataobject->$ident .'\'');
            }
            if (!empty($CFG->dblogerror)) {
                $debug = debug_backtrace();
                foreach ($debug as $d) {
                    if (strpos($d['file'],'datalib') === false) {
                        error_log("SQL ".$db->ErrorMsg()." in {$d['file']} on line {$d['line']}. STATEMENT:  UPDATE $CFG->prefix $table SET $update WHERE $ident = '{$dataobject->$ident}'");
                        break;
                    }
                }
            }
            return false;
        }
    }

}
?>
